//
//  SCNHomeViewController.swift
//  ShoucainuSwift
//
//  Created by 王家旭 on 2017/2/6.
//  Copyright © 2017年 Riluee. All rights reserved.
//

import UIKit
import Alamofire
import Alertift

class SCNHomeViewController: SCNTableViewController {

    fileprivate var headerView: SCNHomeHeaderView!
    
    fileprivate var footView: SCNHomeFootView!
    
    fileprivate var dataObj: SCNHomeMarkerModels?
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        super.viewWillAppear(animated)

    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        super.viewWillDisappear(animated)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        configurationUI()
        
        request()
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccessAction), name: Notification.Name.Login.LoginSuccess, object: nil)
    }

    // MARK: UI
    
    func configurationUI() {
        
//        unowned let weakS = self

//        self.title = "守财奴"
//        let titleImage = UIImageView()
//        titleImage.image = UIImage(named: "icon_logo")
//        titleImage.sizeToFit()
//        self.navigationItem.titleView = titleImage
        self.automaticallyAdjustsScrollViewInsets = false
        
        headerView = SCNHomeHeaderView(frame: CGRect(x: 0, y: 0, width: SCNConstants.SCREENWIDTH, height: 260))
        
        headerView.vc = self
        
        footView = SCNHomeFootView(frame: CGRect(x: 0, y: 0, width: SCNConstants.SCREENWIDTH, height: 90))
        
        footView.footActionClosures = { [weak self] index in
            
            switch index {
            case 0:
                self?.scnPushViewController(SCNAnnouncementViewController())
            case 1:
                self?.scnPushViewController(SCNRankingViewController())
            case 2:
                self?.scnPushViewController(SCNToolsViewController())
            case 3:
                self?.scnPushViewController(SCNStudyViewController())
            case 4:
                
                if SCNSQLiteManager().isLogin() {
                    
                    let user = SCNSQLiteManager().readTable()
                    let tree = user["tree"] as! String
                    if tree == "0" {
                        // 领树
                    
                        Alertift.alert(title: "是否领取您的个人理财树", message: "").action(.default("领取")){
                            SCNRequestManager.postRequest([:], URL: SCNRequestAPI.investTree().createTree, completeBlock: { (result) in
                               
                                self?.noticeOnlyText("理财树领取成功，让我们来共同成长吧")
                                SCNSQLiteManager().updateTree(tree, newType: "1")
                                self?.scnPushViewController(SCNSignInViewController())
                            })
                            }
                            .action(.cancel("取消"))
                            .show()
                    }else {
                        self?.scnPushViewController(SCNSignInViewController())
                    }
                    
                    
                }else {
                    let nav = UINavigationController(rootViewController: LoginViewController())
                    self?.present(nav, animated: true, completion: nil)
                }
                
            default:
                fatalError()
            }
            
        }
        
        self.createTableView(.zero, style: .plain, isRefreshNewData: true, isRefreshMoreData: false) { [unowned self] (table) in
            
            table.tableHeaderView = self.headerView
            
            table.tableFooterView = self.footView
            
            table.rowHeight = UIDevice.current.isiPhoneX() ? SCNConstants.SCREENHEIGHT - 350 - 83 : UIDevice.current.isiPhone6p() ? SCNConstants.SCREENHEIGHT - 350 - 49 : 274
            
            table.register(SCNHomeTableViewCell.classForCoder(), forCellReuseIdentifier: NSStringFromClass(SCNHomeTableViewCell.classForCoder()))
        }


        self.tableView.snp.makeConstraints { (make) in
            make.leading.trailing.top.equalToSuperview()
            make.height.equalToSuperview()
        }
        
        // 适配iOS 11
        extendedLayoutIncludesOpaqueBars = true;
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false;
        };
        tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0)
        tableView.scrollIndicatorInsets = tableView.contentInset
    }
    
    // MARK: DATA
    func requestServer() {
        
        
        
        let param = [
            "device_os": String(UIDevice.current.systemVersion),
            "device_width": String(describing: SCNConstants.SCREENWIDTH),
            "device_height": String(describing: SCNConstants.SCREENHEIGHT),
            "device_token":String(UIDevice.current.systemName)
        ]
        
        SCNHomeViewModels().requestIndexInitNew(param, successBlock: { [unowned self] (dataresult) in
            
            /// header 数据
            if let tmp = dataresult.banner {
                
                self.headerView.banners = tmp
                
            }
            
            if let tender = dataresult.tender_sum {
                self.headerView.investMoneyLabel.text = "\(tender) 元"
                self.headerView.investMoneyLabel.attributedText = String().changeAttributedString(self.headerView.investMoneyLabel.text!, range: NSRange(location: 0, length: (self.headerView.investMoneyLabel.text?.characters.count)! - 1), font: 21, color: SCNConstants.colorWithHexString("fea100"))
            }
            if let rate = dataresult.rate_sum {
                self.headerView.incomeMoneyLabel.text = "\(rate) 元"
                self.headerView.incomeMoneyLabel.attributedText = String().changeAttributedString(self.headerView.incomeMoneyLabel.text!, range: NSRange(location: 0, length: (self.headerView.incomeMoneyLabel.text?.characters.count)! - 1), font: 21, color: SCNConstants.colorWithHexString("fea100"))
            }
            if let list = dataresult.list {
                // 测试
//                let  index = arc4random_uniform(UInt32(list.count - 1))
                self.dataObj = list[0]
            }
            
            self.tableView.reloadData()
        }) 
    }
    
    // MARK: ACTION

    override func request() {
        super.request()
        self.requestServer()
    }
    
    func loginSuccessAction() {
        requestServer()
    }
    
    
}

extension SCNHomeViewController {


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(SCNHomeTableViewCell.classForCoder()), for: indexPath) as! SCNHomeTableViewCell

        cell.selectionStyle = .none

        cell.model = dataObj
        
//        dump(dataObj) 对象的镜像 进行标准输出
        
        return cell

    }


}
